package api

import (
	"errors"
	global2 "longmen/server/config/global"
	"longmen/server/internal/services/consumers/publisher"
	_const "longmen/server/pkg/common/helper/const"
	string2 "longmen/server/pkg/common/helper/string"
	time2 "longmen/server/pkg/common/helper/timehelper"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/grpc_client"
	protobuf2 "longmen/server/pkg/protobuf"
	"time"

	"longmen/server/pkg/common/api_models"

	"github.com/labstack/echo/v4"
	"github.com/spf13/cast"
	"google.golang.org/grpc/status"
)

// @Summary 首页热门赛事滚动卡  爬虫数据专用
// @Description 首页热门赛事滚动卡 爬虫数据专用
// @Accept  json
// @Produce  json
// @Tags Match
// @Success 200 {object} api_models.MatchCard4Crawler "result"
// @Router /api/match/getHotMatchCards4Crawler [POST]
func (base *Controller) GetHotMatchCards4Crawler(c echo.Context) error {
	uid := c.Get("uid")
	global2.Log.Debugf("uid:%v", uid)
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	resp, err := grpc_client.GrpcSportServer.GetHotMatchCards4Crawler(ctx, &protobuf2.GetHotMatchCards4CrawlerReq{UserId: cast.ToUint32(uid)})
	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, _const.EMPTY_STR, err)
	}
	matchCard := make([]*api_models.MatchCard4Crawler, 0)
	for _, matchCards := range resp.GetGetHotMatchCards4Crawler() {
		var sportType string
		switch matchCards.SportId {
		case 1:
			sportType = "football"
		case 2:
			sportType = "basket"
		}
		matchCard = append(matchCard, &api_models.MatchCard4Crawler{
			ID:                int(matchCards.Id),
			Status:            int(matchCards.MatchStatus),
			Time:              matchCards.MatchTime, //纳秒时间戳转化为秒时间戳
			HomeScore:         int(matchCards.HomeScore),
			AwayScore:         int(matchCards.AwayScore),
			SportType:         sportType,
			HomeTeamLogo:      matchCards.HomeLogo,
			HomeTeamNameZH:    matchCards.Home,
			AwayTeamLogo:      matchCards.AwayLogo,
			AwayTeamNameZH:    matchCards.Away,
			EventLogo:         matchCards.CompLogo,
			EventNameZH:       matchCards.Comp,
			MatchStatus:       matchCards.MatchStatus,
			MatchDetailStatus: matchCards.MatchDetailStatus,
			TimePlayed:        matchCards.TimePlayed,
			MatchId:           int(matchCards.MatchId),
			SportId:           int(matchCards.SportId),
			AnchorAvatars:     matchCards.AnchorAvatars,
			AnchorIds:         matchCards.AnchorIds,
			ISReservation:     matchCards.Favorite,
		})
	}
	return util.BuildSuccess(c, matchCard, _const.EMPTY_STR)
}

// @Summary 首页推荐的赛事  爬虫数据专用
// @Description 首页推荐的赛事  爬虫数据专用
// @Accept  json
// @Produce  json
// @Tags Match
// @Param   sendBody body api_models.GetRecommendMatches4CrawlerReq true "body"
// @Success 200 {object} protobuf.GetRecommendMatches4CrawlerResp "result"
// @Router /api/match/getRecommendMatches4Crawler [POST]
func (base Controller) GetRecommendMatches4Crawler(c echo.Context) error {
	r := &protobuf2.GetRecommendMatches4CrawlerReq{}
	if err := util.Json2Struct(c.Get(_const.HTTP_KEY_BODY).(string), r); err != nil {
		return util.BadParam(c, err)
	}
	if err := _const.Validate.Struct(r); err != nil {
		return util.BadParam(c, err)
	}
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	resp, err := grpc_client.GrpcSportServer.GetRecommendMatches4Crawler(ctx, r)
	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, status.Convert(err).Message(), err)
	}
	return util.BuildSuccess(c, resp, _const.EMPTY_STR)
}

// @Summary 联赛信息 爬虫数据专用
// @Description 联赛信息 爬虫数据专用
// @Accept  json
// @Produce  json
// @Tags Match
// @Param   sendBody body api_models.GetCompetation4CrawlerReq true "body"
// @Success 200 {object} api_models.GetCompetation4CrawlerResp "result"
// @Router /api/match/getCompetation4Crawler [POST]
func (base *Controller) GetCompetation4Crawler(c echo.Context) error {
	req := &protobuf2.GetCompetation4CrawlerReq{}
	if err := util.Json2Struct(c.Get(_const.HTTP_KEY_BODY).(string), req); err != nil {
		return util.BadParam(c, err)
	}
	if err := _const.Validate.Struct(req); err != nil {
		return util.BadParam(c, err)
	}
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	resp, err := grpc_client.GrpcSportNewServer.GetCompetation4Crawler(ctx, req)
	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, _const.EMPTY_STR, err)
	}
	return util.BuildSuccess(c, resp.CompList, _const.EMPTY_STR)
}

// @Summary 获取赛事 爬虫数据专用
// @Description 获取赛事 爬虫数据专用
// @Accept  json
// @Produce  json
// @Tags Match
// @Param   sendBody body api_models.GetMatch4CrawlerReq true "body"
// @Success 200 {object} api_models.GetMatch4CrawlerResp "result"
// @Router /api/match/getMatch4Crawler [POST]
func (base *Controller) GetMatch4Crawler(c echo.Context) error {
	req := &protobuf2.GetMatch4CrawlerReq{}
	if err := util.Json2Struct(c.Get(_const.HTTP_KEY_BODY).(string), req); err != nil {
		return util.BadParam(c, err)
	}
	if err := _const.Validate.Struct(req); err != nil {
		return util.BadParam(c, err)
	}
	req.Page = int32(string2.GetDefaultNum(int(req.Page), 1))
	req.Size = int32(string2.GetDefaultNum(int(req.Size), 8))
	req.Uid = cast.ToUint32(c.Get(_const.HTTP_KEY_UID))
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	resp, err := grpc_client.GrpcSportNewServer.GetMatch4Crawler(ctx, req)
	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, _const.EMPTY_STR, err)
	}
	// 原因是rpc切片返回为空，前端需要对像[]
	if len(resp.Match) > 0 {
		for _, match := range resp.Match {
			if len(match.Reservation) == 0 {
				match.Reservation = make([]*protobuf2.Reservation, 0)
			}
		}
	}
	return util.BuildSuccess(c, resp, _const.EMPTY_STR)
}

// @Summary 获取今天联赛的赛事联赛名称（直播）
// @Description  获取今天联赛的赛事联赛名称(直播)
// @Accept  json
// @Produce  json
// @Tags Match
// @Param   sendBody body protobuf.SportLiveMatchReq true "body"
// @Success 200 {object} protobuf.SportLiveMatchCompResp "result"
// @Router /api/match/getSportMatchComp [POST]
func (base *Controller) GetSportMatchComp(c echo.Context) error {
	req := &protobuf2.SportLiveMatchReq{}
	if err := util.Json2Struct(c.Get(_const.HTTP_KEY_BODY).(string), req); err != nil {
		return util.BadParam(c, err)
	}
	if err := _const.Validate.Struct(req); err != nil {
		return util.BadParam(c, err)
	}
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	resp, err := grpc_client.GrpcSportServer.SportLiveMatchComp(ctx, req)
	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, _const.EMPTY_STR, err)
	}
	return util.BuildSuccess(c, resp, _const.EMPTY_STR)
}

// @Summary 根据联赛名获取赛事
// @Description 根据联赛名获取赛事
// @Accept  json
// @Produce  json
// @Tags Match
// @Param   sendBody body protobuf.SportLiveMatchReq true "body"
// @Success 200 {object} protobuf.SportLiveMatchResp "result"
// @Router /api/match/getSportMatch [POST]
func (base *Controller) GetSportMatch(c echo.Context) error {
	req := &protobuf2.SportLiveMatchReq{}
	if err := util.Json2Struct(c.Get(_const.HTTP_KEY_BODY).(string), req); err != nil {
		return util.BadParam(c, err)
	}
	if err := _const.Validate.Struct(req); err != nil {
		return util.BadParam(c, err)
	}
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	resp, err := grpc_client.GrpcSportServer.SportLiveMatch(ctx, req)
	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, _const.EMPTY_STR, err)
	}
	return util.BuildSuccess(c, resp, _const.EMPTY_STR)
}

// @Summary 用户预约赛事 爬虫数据专用 需登入
// @Description 用户预约赛事  爬虫数据专用 需登入
// @Accept  json
// @Produce  json
// @Tags Match
// @Param   sendBody body api_models.ReserveOrCancelReserveMatchReq true "body"
// @Success 200 {object} api_models.ReserveOrCancelReserveMatchResp "result"
// @Router /api/match/reserveMatch4Crawler [POST]
func (base *Controller) ReserveMatch4Crawler(c echo.Context) error {
	req := &protobuf2.ReservationReq{}
	if err := util.Json2Struct(c.Get(_const.HTTP_KEY_BODY).(string), req); err != nil {
		return util.BadParam(c, err)
	}
	user, err := base.GetUserByCtx(c)
	if err != nil {
		return util.BuildLoginTimeOut(c, err)
	}
	// m := new(api_models.ReserveOrCancelReserveMatchReq)
	// if err := util2.Json2Struct(c.Get(util2.HTTP_KEY_BODY).(string), m); err != nil {
	// 	return common.BadParam(c, err)
	// }
	//重新赋值
	r := &protobuf2.ReserveMatch4CrawlerReq{}
	r.UserId = int32(user.Id)
	r.IsAnchor = int32(user.IsAnchor)
	r.MatchId = int32(req.MatchId)
	r.LiveTime = req.LiveTime
	if err := util.Json2Struct(c.Get(_const.HTTP_KEY_BODY).(string), r); err != nil {
		return util.BadParam(c, err)
	}
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	resp, err := grpc_client.GrpcSportNewServer.ReserveMatch4Crawler(ctx, r)
	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, _const.EMPTY_STR, err)
	}
	return util.BuildSuccess(c, resp, _const.EMPTY_STR)
}

// @Summary 获取用户预约的赛事 爬虫数据专用 需登入
// @Description 获取用户预约的赛事  爬虫数据专用 需登入
// @Accept  json
// @Produce  json
// @Tags Match
// @Param   sendBody body api_models.GetReservedMatch4CrawlerReq true "body"
// @Success 200 {object} api_models.GetReservedMatch4CrawlerResp "result"
// @Router /api/match/getReservedMatch4Crawler [POST]
func (base *Controller) GetReservedMatch4Crawler(c echo.Context) error {
	user, err := base.GetUserByCtx(c)
	if err != nil {
		return util.BuildLoginTimeOut(c, err)
	}
	//resp, err := base.Service.GetReservedMatch4Crawler(user.Id)
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	resp, err := grpc_client.GrpcSportNewServer.GetReservedMatch4Crawler(ctx, &protobuf2.GetReservedMatch4CrawlerReq{UserId: int64(user.Id)})
	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, _const.EMPTY_STR, err)
	}
	//return common.BuildSuccess(c, resp, util.EMPTY_STR)
	return util.BuildSuccess(c, resp.Item, _const.EMPTY_STR)
}

// @Summary 用户取消预约赛事 爬虫数据专用 需登入
// @Description 用户取消预约赛事  爬虫数据专用 需登入
// @Accept  json
// @Produce  json
// @Tags Match
// @Param   sendBody body api_models.ReserveOrCancelReserveMatchReq true "body"
// @Success 200 {object} api_models.ReserveOrCancelReserveMatchResp "result"
// @Router /api/match/cancelReserveMatch4Crawler [POST]
func (base *Controller) CancelReserveMatch4Crawler(c echo.Context) error {
	user, err := base.GetUserByCtx(c)
	if err != nil {
		return util.BuildLoginTimeOut(c, err)
	}
	m := new(api_models.ReserveOrCancelReserveMatchReq)
	if err := util.Json2Struct(c.Get(_const.HTTP_KEY_BODY).(string), m); err != nil {
		return util.BadParam(c, err)
	}
	r := &protobuf2.ReserveMatch4CrawlerReq{}
	r.UserId = int32(user.Id)
	r.IsAnchor = int32(user.IsAnchor)
	r.MatchId = int32(m.MatchId)
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	resp, err := grpc_client.GrpcSportNewServer.CancelReserveMatch4Crawler(ctx, r)
	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, _const.EMPTY_STR, err)
	}
	return util.BuildSuccess(c, resp, _const.EMPTY_STR)
}

// @Summary 赛程筛选菜单(移动端)
// @Description 赛程筛选菜单(移动端)
// @Accept  json
// @Produce  json
// @Tags Match
// @Param   sendBody body protobuf.GetMatchListReq true "body"
// @Success 200 {object} protobuf.CompMenuItemResp "result"
// @Router /api/match/getCompMenuList [POST]
func (base *Controller) GetCompMenuList(c echo.Context) error {
	req := &protobuf2.GetMatchListReq{}
	if err := util.Json2Struct(c.Get(_const.HTTP_KEY_BODY).(string), req); err != nil {
		return util.BadParam(c, err)
	}
	//增加开关
	matchSwitch := global2.Config.GetIntOrDefault("match.hide.switch", 0)
	if matchSwitch > 0 {
		if req.MatchStatus != _const.DEF_MATCH_STATUS_FAVORITE {
			req.MatchStatus = 777
		}
	}
	if req.MatchStatus == _const.DEF_MATCH_STATUS_HOT && req.SportId == 999 {
		return util.BuildFail(c, _const.RPC_FAILED, _const.EMPTY_STR, errors.New("焦点中无热门赛事"))
	}
	// req.MatchStatus!=util.DEF_MATCH_STATUS_FAVORITE 收藏无赛事筛选功能
	if req.MatchStatus != _const.DEF_MATCH_STATUS_ALL &&
		req.MatchStatus != _const.DEF_MATCH_STATUS_ACTION &&
		req.MatchStatus != _const.DEF_MATCH_STATUS_HOT &&
		//req.MatchStatus != util.DEF_MATCH_SEARCH &&
		req.MatchStatus != _const.DEF_MATCH_STATUS_MATCH &&
		req.MatchStatus != _const.DEF_MATCH_STATUS_DONE {
		return util.BuildFail(c, _const.RPC_FAILED, _const.EMPTY_STR, errors.New("请输入正确的赛事状态"))
	}
	if req.SportId <= 0 {
		return util.BuildFail(c, _const.RPC_FAILED, _const.EMPTY_STR, errors.New("请输入正确的赛事类别"))
	}
	if _, err := time.Parse(time2.TIME_LAYOUT_FORMAT_4, req.Date); err != nil {
		return util.BuildFail(c, _const.RPC_FAILED, _const.EMPTY_STR, errors.New("日期格式不对"))
	}
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	list, err := grpc_client.GrpcSportNewServer.GetCompMenuList(ctx, req)
	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, _const.EMPTY_STR, err)
	}
	return util.BuildSuccess(c, list, _const.EMPTY_STR)
}

// @Summary 赛程列表(移动端)
// @Description 赛程列表(移动端)
// @Accept  json
// @Produce  json
// @Tags Match
// @Param   sendBody body protobuf.GetMatchListReq true "body"
// @Success 200 {object} protobuf.MatchResp "result"
// @Router /api/match/getMatchList [POST]
func (base *Controller) GetMatchList(c echo.Context) error {

	req := &protobuf2.GetMatchListReq{}
	if err := util.Json2Struct(c.Get(_const.HTTP_KEY_BODY).(string), req); err != nil {
		return util.BadParam(c, err)
	}
	req.UserId = cast.ToUint64(c.Get(_const.HTTP_KEY_UID))
	matchSwitch := global2.Config.GetIntOrDefault("match.hide.switch", 0)
	//增加开关
	if matchSwitch > 0 {
		if req.MatchStatus != _const.DEF_MATCH_STATUS_FAVORITE {
			req.MatchStatus = 777
		}
	}
	if req.MatchStatus == _const.DEF_MATCH_STATUS_HOT && req.SportId == 999 {
		return util.BuildFail(c, _const.RPC_FAILED, _const.EMPTY_STR, errors.New("焦点中无热门赛事"))
	}
	if req.MatchStatus != _const.DEF_MATCH_STATUS_ALL &&
		req.MatchStatus != _const.DEF_MATCH_STATUS_ACTION &&
		req.MatchStatus != _const.DEF_MATCH_STATUS_HOT &&
		req.MatchStatus != _const.DEF_MATCH_SEARCH &&
		req.MatchStatus != _const.DEF_MATCH_STATUS_MATCH &&
		req.MatchStatus != _const.DEF_MATCH_STATUS_DONE &&
		req.MatchStatus != _const.DEF_MATCH_STATUS_FAVORITE {
		return util.BuildFail(c, _const.RPC_FAILED, _const.EMPTY_STR, errors.New("请输入正确的赛事状态"))
	}
	if req.MatchStatus != _const.DEF_MATCH_SEARCH && req.SportId <= 0 {
		return util.BuildFail(c, _const.RPC_FAILED, _const.EMPTY_STR, errors.New("请输入正确的赛事类别"))
	}

	//用户ID未有登陆
	if req.UserId <= 0 && req.MatchStatus == _const.DEF_MATCH_STATUS_FAVORITE {
		return util.BuildFail(c, _const.RPC_FAILED, _const.EMPTY_STR, errors.New("点击收藏夹,必须先登陆!"))
	}

	if req.MatchStatus != _const.DEF_MATCH_SEARCH && req.MatchStatus != _const.DEF_MATCH_STATUS_ALL {
		if _, err := time.Parse(time2.TIME_LAYOUT_FORMAT_4, req.Date); err != nil {
			return util.BuildFail(c, _const.RPC_FAILED, _const.EMPTY_STR, errors.New("日期格式不对!"))
		}
	}
	if req.MatchStatus == _const.DEF_MATCH_SEARCH && len(req.MatchName) <= 0 {
		return util.BuildFail(c, _const.RPC_FAILED, _const.EMPTY_STR, errors.New("赛事搜索名称不能为空!"))
	}
	req.Page = int32(string2.GetDefaultNum(int(req.Page), _const.LIST_PAGE_DEFAULT))
	req.Size = int32(string2.GetDefaultNum(int(req.Size), _const.LIST_SIZE_DEFAULT))
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	list, err := grpc_client.GrpcSportNewServer.GetMatchList(ctx, req)
	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, _const.EMPTY_STR, err)
	}
	return util.BuildSuccess(c, list, _const.EMPTY_STR)
}

// @Summary 赛事比分
// @Description 赛事比分
// @Accept  json
// @Produce  json
// @Tags Match
// @Param   sendBody body protobuf.GetMatchScoreListReq true "body"
// @Success 200 {object} protobuf.MatchScoreResp "result"
// @Router /api/match/getMatchScoreList [POST]
func (base *Controller) GetMatchScoreList(c echo.Context) error {

	req := &protobuf2.GetMatchScoreListReq{}
	if err := util.Json2Struct(c.Get(_const.HTTP_KEY_BODY).(string), req); err != nil {
		return util.BadParam(c, err)
	}
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	list, err := grpc_client.GrpcSportNewServer.GetMatchScoreList(ctx, req)
	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, _const.EMPTY_STR, err)
	}
	return util.BuildSuccess(c, list, _const.EMPTY_STR)
}

// @Summary 收藏赛事/取消收藏(移动端)
// @Description 收藏赛事/取消收藏(移动端)
// @Accept  json
// @Produce  json
// @Tags Match
// @Param   sendBody body protobuf.FavoriteReq true "body"
// @Success 200 {object} protobuf.FavoriteResp "result"
// @Router /api/match/favoriteMatch [POST]
func (base *Controller) FavoriteMatch(c echo.Context) error {
	req := &protobuf2.FavoriteReq{}
	if err := util.Json2Struct(c.Get(_const.HTTP_KEY_BODY).(string), req); err != nil {
		return util.BadParam(c, err)
	}
	if req.MatchId <= 0 {
		return util.BuildFail(c, _const.RPC_FAILED, _const.EMPTY_STR, errors.New("赛事ID不能为空或小于0"))
	}
	if req.Operate != _const.FAVORITE_SUBSCRIBE &&
		req.Operate != _const.FAVORITE_CANCEL {
		return util.BuildFail(c, _const.RPC_FAILED, _const.EMPTY_STR, errors.New("没有此收藏操作方式"))
	}
	if uid, ok := c.Get(_const.HTTP_KEY_UID).(int); ok {
		req.UserId = int32(uid)
	}
	if req.UserId <= 0 {
		return util.BuildFail(c, _const.RPC_FAILED, _const.EMPTY_STR, errors.New("点击收藏夹,必须先登陆!"))
	}
	if req.MatchId <= 0 {
		return util.BuildFail(c, _const.RPC_FAILED, _const.EMPTY_STR, errors.New("赛事ID不能为空!"))
	}
	if req.SportId <= 0 {
		return util.BuildFail(c, _const.RPC_FAILED, _const.EMPTY_STR, errors.New("赛事类别不能为空!"))
	}
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	favorite, err := grpc_client.GrpcSportNewServer.FavoriteMatch(ctx, req)
	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, _const.EMPTY_STR, err)
	}
	if favorite.Code == 1 {
		return util.BuildFail(c, _const.RPC_FAILED, "操作失败,不能重复提交", errors.New("操作失败,不能重复提交"))
	}
	return util.BuildSuccess(c, favorite, _const.EMPTY_STR)
}

// @Summary 会员收藏赛事总条数(移动端)
// @Description 会员收藏赛事总条数(移动端)
// @Accept  json
// @Produce  json
// @Tags Match
// @Param   sendBody body protobuf.CountUserFavoriteReq true "body"
// @Success 200 {object} protobuf.UserFavoriteResp "result"
// @Router /api/match/countUserFavorite [POST]
func (base *Controller) CountUserFavorite(c echo.Context) error {
	req := &protobuf2.CountUserFavoriteReq{}
	if err := util.Json2Struct(c.Get(_const.HTTP_KEY_BODY).(string), req); err != nil {
		return util.BadParam(c, err)
	}
	if uid, ok := c.Get(_const.HTTP_KEY_UID).(int); ok {
		req.UserId = int32(uid)
	}
	if req.UserId <= 0 {
		return util.BuildFail(c, _const.RPC_FAILED, _const.EMPTY_STR, errors.New("统计会员收藏赛事数量,请先登陆!"))
	}
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	favorite, err := grpc_client.GrpcSportNewServer.CountUserFavorite(ctx, req)
	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, _const.EMPTY_STR, err)
	}

	return util.BuildSuccess(c, favorite, _const.EMPTY_STR)
}

// @Summary 根据赛事ID 查询赛事信息
// @Description 根据赛事ID 查询赛事信息
// @Accept  json
// @Produce  json
// @Tags Match
// @Param   sendBody body protobuf.GetMatchByIdReq true "body"
// @Success 200 {object} protobuf.Match "result"
// @Router /api/match/getMatchById [POST]
func (base Controller) GetMatchById(c echo.Context) error {
	r := &protobuf2.GetMatchByIdReq{}
	if err := util.Json2Struct(c.Get(_const.HTTP_KEY_BODY).(string), r); err != nil {
		return util.BadParam(c, err)
	}
	if err := _const.Validate.Struct(r); err != nil {
		return util.BadParam(c, err)
	}
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	resp, err := grpc_client.GrpcSportNewServer.GetMatchById(ctx, r)

	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, status.Convert(err).Message(), err)
	}
	return util.BuildSuccess(c, resp, _const.EMPTY_STR)
}

// @Summary 获取赛事直播链接
// @Description 获取赛事直播链接
// @Accept  json
// @Produce  json
// @Tags Match
// @Param   sendBody body protobuf.GetMatchByIdReq true "body"
// @Success 200 {object} protobuf.Match "result"
// @Router /api/match/getMatchLiveUrl [POST]
func (base Controller) MatchLiveUrl(c echo.Context) error {
	r := &protobuf2.MatchLiveUrlReq{}
	if err := util.Json2Struct(c.Get("body").(string), r); err != nil {
		return util.BadParam(c, err)
	}
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	resp, err := grpc_client.GrpcSportNewServer.MatchLiveUrl(ctx, r)
	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, "", err)
	}
	return util.BuildSuccess(c, resp, "")
}

// @Summary 55直播赛事列表
// @Description 55直播赛事列表
// @Accept  json
// @Produce  json
// @Tags Match
// @Param   sendBody body protobuf.Get55MachListReq true "body"
// @Success 200 {object} protobuf.GetRecommendMatches4CrawlerResp "result"
// @Router /api/match/get55MatchList [POST]
func (base Controller) Get55MatchList(c echo.Context) error {
	r := &protobuf2.Get55MachListReq{}
	if err := util.Json2Struct(c.Get("body").(string), r); err != nil {
		return util.BadParam(c, err)
	}

	r.ReqSource = 1
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	//阻止短时间大量访问, 每秒限制
	if util.NeedIPRateLimit(c.RealIP(), 20) {
		return util.BuildFail(c, 1, "访问次数超过限制", nil)
	}
	resp, err := grpc_client.GrpcSportServer.Get55MachList(ctx, r)
	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, "", err)
	}
	return util.BuildSuccess(c, resp, "")
}

// @Summary SEO直播赛事列表
// @Description SEO直播赛事列表
// @Accept  json
// @Produce  json
// @Tags Match
// @Param   sendBody body protobuf.Get55MachListReq true "body"
// @Success 200 {object} protobuf.GetRecommendMatches4CrawlerResp "result"
// @Router /api/match/get55MatchList2 [POST]
func (base Controller) GetSeoMatchList(c echo.Context) error {
	r := &protobuf2.Get55MachListReq{}
	if err := util.Json2Struct(c.Get("body").(string), r); err != nil {
		return util.BadParam(c, err)
	}
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()

	allowIps := []string{"38.55.250.125"}
	maxReqLimit := 20
	ip := c.RealIP()
	for _, allowIp := range allowIps {
		if allowIp == ip {
			maxReqLimit = 40
			break
		}
	}
	//阻止短时间大量访问, 每秒限制
	if util.NeedIPRateLimit(ip, maxReqLimit) {
		global2.Log.Errorf("GetSeoMatchList 访问次数超过限制 | ip:%v", ip)
		return util.BuildFail(c, 1, "访问次数超过限制", nil)
	}
	resp, err := grpc_client.GrpcSportServer.Get55MachList(ctx, r)
	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, "", err)
	}
	return util.BuildSuccess(c, resp, "")
}

// @Summary 55直播赛程
// @Description 55直播赛程
// @Accept  json
// @Produce  json
// @Tags Match
// @Param   sendBody body protobuf.Empty true "body"
// @Success 200 {object} protobuf.Get55HotLeagueResp "result"
// @Router /api/match/get55HotLeague [POST]
func (base Controller) Get55HotLeague(c echo.Context) error {
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	resp, err := grpc_client.GrpcSportServer.Get55HotLeague(ctx, &protobuf2.Empty{})
	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, "", err)
	}
	return util.BuildSuccess(c, resp, "")
}

// @Summary 生成验签字符串
// @Description 生成验签字符串
// @Accept  json
// @Produce  json
// @Tags Match
// @Param   sendBody body api_models.SignAuth true "body"
// @Success 200 {object} string "result"
// @Router /api/match/getSign [POST]
/*func (base *Controller) GetSign(c echo.Context) error {
	signAuth := &api_models.SignAuth{}
	if err := util.Json2Struct(c.Get(util.HTTP_KEY_BODY).(string), signAuth); err != nil {
		return common.BadParam(c, err)
	}
	versionMap := make(map[string]string)

	versionMap["version1"] = "qwertyuiaadfaopasdfghj111klzxcvbnmQWERTYUIOPASDFGHJKLZX12311CVBNM123456dadfasddsadad7890"
	versionMap["version2"] = "qwertyuiopaaaaaas1231dfghjklzxcvbn121mQWERTYUIOPA1231SDFGHJKLZXCaddddVBNM12dadd34567addadf"
	versionMap["version3"] = "qwertyuiopaadfaadaddsd121fghjklzxcvbnmQWERTYUIOadfadweradfPASDFGHJKaadLZXCVBN112M1dadf2345addadd0"
	var md5Str string
	if keys, ok1 := versionMap[signAuth.Version]; ok1 {
		//从扰乱码中找到字符
		s := (signAuth.SignDate + int64(signAuth.DisturbCode)) % int64(len(keys))
		//找到MD5中需要替换的字符
		r := (signAuth.SignDate + int64(signAuth.DisturbCode)) % 32
		signStr := resSingStr(signAuth)
		sumMd5 := md5.Sum([]byte(signStr))
		md5Str = fmt.Sprintf("%x", sumMd5)
		tarStr := md5Str[r : r+1]
		scrStr := keys[s : s+1]
		md5Str = strings.ReplaceAll(md5Str, tarStr, scrStr)
		md5Str = strings.ToTitle(md5Str)

		//msg := fmt.Sprintf("sginStr:=%s md5Str:=%s", signStr, md5Str)
		//global.Log.Error(msg, errors.New("验签错误"))
		//return errors.New("验签错误")
	}
	return common.BuildSuccess(c, md5Str, util.EMPTY_STR)
}*/

/**
 * @Author willi
 * @Description //TODO
 * @Date 15:17 2022/9/21
 * @Param
 * @return
 **/
/*func resSingStr(signAuth *api_models.SignAuth) string {
	var strBuilder strings.Builder
	strBuilder.WriteString("method=")
	strBuilder.WriteString(signAuth.Method)
	strBuilder.WriteString("&uid=")
	if signAuth.Uid > 0 {
		strBuilder.WriteString(cast.ToString(signAuth.Uid))
	}
	strBuilder.WriteString("&signDate=")
	strBuilder.WriteString(cast.ToString(signAuth.SignDate))
	strBuilder.WriteString("&version=")
	strBuilder.WriteString(signAuth.Version)
	return strBuilder.String()
}*/

// @Summary 赛事积分榜
// @Description 赛事积分榜
// @Accept  json
// @Produce  json
// @Tags Match
// @Param   sendBody body protobuf.Empty true "body"
// @Success 200 {object} protobuf.CompointListResp "result"
// @Router /api/event/point [POST]
func (base Controller) Compint(c echo.Context) error {
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	resp, err := grpc_client.GrpcSportServer.Compoint(ctx, &protobuf2.Empty{})
	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, "", err)
	}

	// 推送使用统计
	err = global2.PublisherStatistic.StatisticPush(
		publisher.UsageStatistic, base.GetAuthUserId(c), base.GetDeviceInfo(c), c.RealIP(), base.GetPlatform(c),
	)
	if err != nil {
		global2.Log.Infof("stats error: %v", err)
	}

	return util.BuildSuccess(c, resp, "")
}

// 积分榜到详情赛事
func (base Controller) PointTeamDetail(c echo.Context) error {
	r := &protobuf2.PointTeamDetailReq{}
	if err := util.Json2Struct(c.Get("body").(string), r); err != nil {
		return util.BadParam(c, err)
	}
	user, _ := base.GetUserByCtx(c)
	r.UserId = int64(user.Id)
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	resp, err := grpc_client.GrpcSportServer.PointTeamDetail(ctx, r)
	if err != nil {
		return util.GrpcError(c, _const.RPC_FAILED, "", err)
	}
	return util.BuildSuccess(c, resp, "")
}
